﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using iOak.Domain.Resumes;
using System.Web.UI;
using System.Web.UI.WebControls;
using iOak.Common.Untity;
using iOak.Business.Resumes;
using iOak.Domain.Campaigns;
using System.Transactions;
using iOak.Business.Campaigns;

namespace iOak.Web.TemplateHelper
{
    public static class TemplateCommonHelper
    {
        private static readonly ResumeTemplateService itemResumeTemplateService = new ResumeTemplateService();
        private static readonly ResumeFieldService itemResumeFieldService = new ResumeFieldService();
        private static readonly ResumeTemplateFieldsService itemResumeTemplateFieldsService = new ResumeTemplateFieldsService();
        private static readonly ResumeDetailService itemResumeDetailService = new ResumeDetailService();
        private static readonly ResumeService itemResumeService = new ResumeService();
        private static readonly ApplicationService itemApplicationService = new ApplicationService();
        private static readonly ApplicationCandidateService itemApplicationCandidateService = new ApplicationCandidateService();

        /// <summary>
        /// 获取模板元数据对象
        /// </summary>
        /// <param name="templateId">模板ID</param>
        /// <returns>元数据对象</returns>
        public static List<ResumeField> GetTemplateFileList(Guid templateId)
        {
            // 获取默认控件
            var listDefault = itemResumeFieldService.GetDefaultFieldList();

            // 获取模板控件
            var templateList = itemResumeTemplateFieldsService.GetListByTemplateId(templateId);

            // 转换对象
            var changeList = itemResumeTemplateFieldsService.ChangeListToField(templateList);
            itemResumeFieldService.AddDefaultList(changeList, listDefault);

            return changeList;
        }

        /// <summary>
        /// 控件初始化
        /// </summary>
        /// <param name="resumeFieldList">元数据列表</param>
        /// <param name="templateControl">当前模板</param>
        /// <param name="resumeDetailList">值列表</param>
        public static void InitializationTemplate(List<ResumeField> resumeFieldList, Control templateControl,
            List<ResumeDetail> resumeDetailList, bool readOnly = true)
        {
            resumeFieldList.ForEach(m =>
                {
                    string labelText = m.DisplayName;
                    if (string.IsNullOrWhiteSpace(labelText))
                    {
                        labelText = m.LabelText;
                    }
                    var lableControl = templateControl.FindControl("lbl" + m.FieldName) as Label;
                    var valueItem = resumeDetailList.FirstOrDefault(v => v.Key == m.FieldName);
                    var labelControl = templateControl.FindControl("label" + m.FieldName) as Label;
                    if (labelControl == null)
                    {
                        labelControl = new Label();
                    }
                    if (lableControl != null)
                    {
                        lableControl.Text = labelText;
                    }
                    switch (m.DataType)
                    {
                        case (int)FieldDataType.Text:
                            {
                                var currentControl = templateControl.FindControl("txt" + m.FieldName) as TextBox;

                                if (currentControl == null)
                                {
                                    break;
                                }
                                if (readOnly)
                                {
                                    currentControl.Visible = false;
                                }
                                else
                                {
                                    labelControl.Visible = false;
                                    //  如果是必须输入则添加样式
                                    if (m.Reqiured)
                                    {
                                        currentControl.CssClass = "editor-required";
                                    }

                                    // 添加maxlength
                                    if (m.MaxLength != null)
                                    {
                                        currentControl.MaxLength = (int)m.MaxLength;
                                    }
                                }

                                if (valueItem != null)
                                {
                                    currentControl.Text = valueItem.ValueString;
                                    labelControl.Text = valueItem.ValueString;
                                }
                                break;
                            }
                        case (int)FieldDataType.PickupList:
                            {
                                var currentControl = templateControl.FindControl("ddl" + m.FieldName) as DropDownList;

                                if (currentControl == null)
                                {
                                    break;
                                }
                                if (readOnly)
                                {
                                    currentControl.Visible = false;
                                }
                                else
                                {
                                    labelControl.Visible = false;
                                    currentControl.Items.Clear();

                                    // 获取绑定列表
                                    var listBind = m.DefaultValue.Split(';').ToList();

                                    listBind.ForEach(item =>
                                    {
                                        currentControl.Items.Add(new ListItem(item, item));
                                    });

                                    //  如果是必须输入则添加样式
                                    if (m.Reqiured)
                                    {
                                        currentControl.CssClass = "editor-ddl-required";
                                    }
                                }

                                if (valueItem != null)
                                {
                                    currentControl.SelectedValue = valueItem.ValueString;
                                    labelControl.Text = valueItem.ValueString;
                                }
                                break;
                            }
                        case (int)FieldDataType.CheckBox:
                            {
                                var currentControl = templateControl.FindControl("chk" + m.FieldName) as CheckBox;

                                if (currentControl == null)
                                {
                                    break;
                                }

                                if (readOnly)
                                {
                                    currentControl.Visible = false;
                                }
                                else
                                {
                                    labelControl.Visible = false;
                                }

                                if (valueItem != null)
                                {
                                    currentControl.Checked = Convert.ToBoolean(valueItem.ValueString);
                                    if (Convert.ToBoolean(valueItem.ValueString))
                                    {
                                        labelControl.Text = "是";
                                    }
                                    else
                                    {
                                        labelControl.Text = "否";
                                    }
                                }
                                break;
                            }
                        default:
                            {
                                break;
                            }
                    }


                });
        }

        /// <summary>
        /// 清空控件
        /// </summary>
        /// <param name="resumeFieldList">元数据列表</param>
        /// <param name="templateControl">当前模板</param>
        public static void ClearTemplate(List<ResumeField> resumeFieldList, Control templateControl)
        {
            resumeFieldList.AsParallel().ForAll(m =>
            {
                var lableControl = templateControl.FindControl("lbl" + m.FieldName) as Label;
                if (lableControl != null)
                {
                    lableControl.Text = m.LabelText;
                }
                switch (m.DataType)
                {
                    case (int)FieldDataType.Text:
                        {
                            var currentControl = templateControl.FindControl("txt" + m.FieldName) as TextBox;

                            if (currentControl == null)
                            {
                                break;
                            }
                            currentControl.Text = string.Empty;
                            break;
                        }
                    case (int)FieldDataType.PickupList:
                        {
                            var currentControl = templateControl.FindControl("ddl" + m.FieldName) as DropDownList;

                            if (currentControl == null)
                            {
                                break;
                            }
                            currentControl.Items.Clear();

                            // 获取绑定列表
                            var listBind = m.DefaultValue.Split(';').ToList();

                            listBind.ForEach(item =>
                            {
                                currentControl.Items.Add(new ListItem(item, item));
                            });
                            break;
                        }
                    case (int)FieldDataType.CheckBox:
                        {
                            var currentControl = templateControl.FindControl("chk" + m.FieldName) as CheckBox;

                            if (currentControl == null)
                            {
                                break;
                            }
                            currentControl.Checked = false;
                            break;
                        }
                    default:
                        {
                            break;
                        }
                }
            });
        }

        /// <summary>
        /// 模板保存
        /// </summary>
        /// <param name="template">当前模板对象</param>
        /// <param name="applicationCandidateId">申报人员ID</param>
        /// <param name="applicationId">申报ID</param>
        /// <param name="resumeId">详细ID</param>
        /// <param name="campaignId">活动ID</param>
        public static void TempleSave(Control template, ref string applicationCandidateId, string applicationId,
            string resumeId, string campaignId, string resumeTemplateId)
        {
            using (TransactionScope ts = new TransactionScope())
            {
                var workassistant = new WorkAssistant();

                // 追加状态
                if (string.IsNullOrWhiteSpace(applicationCandidateId))
                {

                    ApplicationCandidate addItem = new ApplicationCandidate();
                    addItem.ApplicationCandidateId = Guid.NewGuid();
                    addItem.ApplicationId = new Guid(applicationId);
                    addItem.CheckedBy = workassistant.CurrentUser.UserId;
                    addItem.CheckerOn = null;
                    addItem.Notes = string.Empty;
                    addItem.Passed = null;
                    addItem.ResumeId = new Guid(resumeId);
                    addItem.Score = null;
                    itemApplicationCandidateService.Create(addItem);

                    applicationCandidateId = addItem.ApplicationCandidateId.ToString();
                }
                else
                {
                    ApplicationCandidate applicationCandidate = itemApplicationCandidateService.Retrieve(Guid.Parse(applicationCandidateId));
                    applicationCandidate.Passed = null;
                    itemApplicationCandidateService.Update(applicationCandidate);
                }

                // 判断当前resume是否已经存在
                var resumeItem = itemResumeService.Retrieve(new Guid(resumeId));

                if (resumeItem == null)
                {
                    resumeItem = new Resume();

                    resumeItem.CreatedBy = workassistant.CurrentUser.UserId;
                    resumeItem.CreatedOn = DateTime.Now;
                    resumeItem.ModifiedBy = workassistant.CurrentUser.UserId;
                    resumeItem.ModifiedOn = DateTime.Now;
                    resumeItem.ResumeId = new Guid(resumeId);
                    resumeItem.ResumeTemplateId = new Guid(resumeTemplateId);

                    itemResumeService.Create(resumeItem);
                }
                else
                {
                    resumeItem.ModifiedBy = workassistant.CurrentUser.UserId;
                    resumeItem.ModifiedOn = DateTime.Now;
                }

                // 先删除详细数据
                itemResumeDetailService.DeleteByResumeId(new Guid(resumeId));

                // 获取元数据
                var filedList = GetTemplateFileList(new Guid(resumeTemplateId));

                // 获取总条数
                int maxCount = filedList.Count;

                // 输入条数
                int inputCount = 0;

                // 便利控件，并且追加详细信息
                filedList.ForEach(m =>
               {
                   var itemResumeDetail = new ResumeDetail();
                   itemResumeDetail.Key = m.FieldName;
                   itemResumeDetail.ResumeDetailId = Guid.NewGuid();
                   itemResumeDetail.ResumeId = new Guid(resumeId);

                   switch (m.DataType)
                   {
                       case (int)FieldDataType.Text:
                           {
                               var currentControl = template.FindControl("txt" + m.FieldName) as TextBox;

                               if (currentControl == null)
                               {
                                   break;
                               }
                               itemResumeDetail.ValueString = currentControl.Text.Trim();
                               if (!string.IsNullOrWhiteSpace(currentControl.Text))
                               {
                                   inputCount++;
                               }
                               break;
                           }
                       case (int)FieldDataType.PickupList:
                           {
                               var currentControl = template.FindControl("ddl" + m.FieldName) as DropDownList;

                               if (currentControl == null)
                               {
                                   break;
                               }
                               itemResumeDetail.ValueString = currentControl.SelectedValue.Trim();
                               if (!string.IsNullOrWhiteSpace(currentControl.SelectedValue))
                               {
                                   inputCount++;
                               }
                               break;
                           }
                       case (int)FieldDataType.CheckBox:
                           {
                               var currentControl = template.FindControl("chk" + m.FieldName) as CheckBox;

                               if (currentControl == null)
                               {
                                   break;
                               }

                               itemResumeDetail.ValueString = currentControl.Checked.ToString();
                               if (currentControl.Checked)
                               {
                                   inputCount++;
                               }
                               break;
                           }
                       default:
                           {
                               break;
                           }
                   }

                   itemResumeDetailService.Create(itemResumeDetail);
               });

                // 计算出比例
                double proportion = Math.Round(inputCount * 1.0 / maxCount * 100);
                resumeItem.Completeness = (int)proportion;
                itemResumeService.Update(resumeItem);

                // 提交数据
                ts.Complete();
            }
        }

        /// <summary>
        /// 从新设定Grid
        /// </summary>
        /// <param name="listResumeField">字段列表</param>
        /// <param name="gvCurrent">当前对象</param>
        public static void SetGridViewColumn(List<ResumeField> listResumeField, GridView gvCurrent)
        {
            dynamic col = gvCurrent.Columns[gvCurrent.Columns.Count - 1];
            dynamic col2 = gvCurrent.Columns[gvCurrent.Columns.Count - 2];
            gvCurrent.Columns.Clear();

            // 重新添加列
            foreach (var item in listResumeField)
            {
                BoundField itemAdd = new BoundField();
                itemAdd.DataField = item.FieldName;
                itemAdd.HeaderText = item.LabelText;
                if (item.Width == 0)
                {
                    itemAdd.ItemStyle.Width = 100;
                }
                else
                {
                    itemAdd.ItemStyle.Width = (Unit)item.Width;
                }
                gvCurrent.Columns.Add(itemAdd);
            }
            gvCurrent.Columns.Add(col2);
            gvCurrent.Columns.Add(col);
        }

        /// <summary>
        /// 循环列表
        /// </summary>
        /// <param name="resumeFieldList"></param>
        /// <param name="templateControl"></param>
        /// <returns></returns>
        public static string SaveCheck(List<ResumeField> resumeFieldList, Control templateControl)
        {
            string strReturn = string.Empty;

            resumeFieldList.ForEach(m =>
            {
                if (!string.IsNullOrWhiteSpace(strReturn))
                {
                    return;
                }
                switch (m.DataType)
                {
                    case (int)FieldDataType.Text:
                        {
                            var currentControl = templateControl.FindControl("txt" + m.FieldName) as TextBox;

                            if (currentControl != null && currentControl.CssClass.Equals("editor-required")
                                && string.IsNullOrWhiteSpace(currentControl.Text))
                            {
                                strReturn = "请输入 " + m.LabelText + "!";
                                return;
                            }

                            // 添加正则表达式
                            if (!string.IsNullOrWhiteSpace(m.Regex))
                            {

                            }
                            break;
                        }
                    case (int)FieldDataType.PickupList:
                        {
                            var currentControl = templateControl.FindControl("ddl" + m.FieldName) as DropDownList;

                            if (currentControl != null && currentControl.CssClass.Equals("editor-ddl-required")
                                && string.IsNullOrWhiteSpace(currentControl.SelectedValue))
                            {
                                strReturn = "请输入 " + m.LabelText + "!";
                                return;
                            }
                            break;
                        }
                    default:
                        {
                            break;
                        }
                }
            });

            return strReturn;
        }
    }
}